const colors = require("colors");

module.exports = {
  development: {
    username: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
    host: process.env.MYSQL_HOST,
    dialect: "mysql",
    timezone: "+08:00",
    logQueryParameters: true,
    logging: (sql) => {
      console.log(highlightSql(sql));
    },
    use_env_variable: "", // 配置环境变量
  },
  // 其他环境配置...
};
/**
 * 高亮SQL语句
 * @param sql
 * @returns {*}
 */
const highlightSql = (sql) => {
  const blueColor = colors.blue.bold; // SELECT 及其后续关键字的颜色
  const greenColor = colors.green.bold; // INSERT 的颜色
  const yellowColor = colors.yellow.bold; // UPDATE 的颜色
  const warnColor = colors.red.bold; // DELETE 的颜色
  const tableColor = colors.red.bold; // 表名的颜色
  const columnColor = colors.yellow.bold;
  const stringColor = colors.green.bold;

  // 分类关键字并分别处理颜色
  const selectKeywords = [
    "SELECT",
    "FROM",
    "WHERE",
    "AND",
    "OR",
    "NOT",
    "IN",
    "LIKE",
    "AS",
    "JOIN",
    "LEFT",
    "OUTER",
    "ON",
    "GROUP",
    "BY",
    "HAVING",
    "ORDER",
    "LIMIT",
    "OFFSET",
    "DISTINCT",
    "COUNT",
    "SUM",
    "AVG",
    "MAX",
    "MIN",
  ];

  const insertKeyword = ["INSERT"];
  const updateKeyword = ["UPDATE"];
  const deleteKeyword = ["DELETE"];

  let highlightedSql = sql;

  // 应用 SELECT 及其后续关键字的颜色
  selectKeywords.forEach((keyword) => {
    const regex = new RegExp(`\\b${keyword}\\b`, "gi");
    highlightedSql = highlightedSql.replace(regex, blueColor(keyword));
  });

  // 应用 INSERT 的颜色
  insertKeyword.forEach((keyword) => {
    const regex = new RegExp(`\\b${keyword}\\b`, "gi");
    highlightedSql = highlightedSql.replace(regex, greenColor(keyword));
  });

  // 应用 UPDATE 的颜色
  updateKeyword.forEach((keyword) => {
    const regex = new RegExp(`\\b${keyword}\\b`, "gi");
    highlightedSql = highlightedSql.replace(regex, yellowColor(keyword));
  });

  // 应用 DELETE 的颜色
  deleteKeyword.forEach((keyword) => {
    const regex = new RegExp(`\\b${keyword}\\b`, "gi");
    highlightedSql = highlightedSql.replace(regex, warnColor(keyword));
  });

  // 表名、列名和字符串的高亮
  highlightedSql = highlightedSql.replace(
    /(`[^`]+`|\b[a-zA-Z_][a-zA-Z0-9_]*)(?=\s*\.(?![a-zA-Z_]))/g,
    (match, p1) => tableColor(p1),
  );
  highlightedSql = highlightedSql.replace(
    /(\b[a-zA-Z_][a-zA-Z0-9_]*)(?=\s*(?:AS\s+[a-zA-Z_][a-zA-Z0-9_]*|,|$))/g,
    columnColor("$1"),
  );
  highlightedSql = highlightedSql.replace(/'([^']*)'/g, stringColor("$&"));

  return highlightedSql;
};
